<script setup>
import { onMounted, ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Download, Upload, Plus, Delete, Search, Refresh } from '@element-plus/icons-vue'
import {
  getReportingPage,
  addReporting,
  updateReporting,
  deleteReporting,
  batchDeleteReporting,
  exportReporting,
  importReporting
} from '@/api/reporting.js'// 封装 axios 请求（路径、方法、responseType 都在这里）
import zhCn from 'element-plus/dist/locale/zh-cn.mjs'
import dayjs from 'dayjs'

/* ====== 统一上传头 ====== */
const uploadHeaders = { Authorization: localStorage.getItem('token') }

/* ====== 导出：axios 下载 ====== */
const handleExport = async () => {
  try {
    const blob = await exportReporting() // 导出接口 axios 返回 blob，不是 JSON
    const fileName = '报到信息.xlsx'// 下载文件名固定，不写会叫 "下载"
    const link = document.createElement('a') // 创建临时 <a> 标签
    link.href = window.URL.createObjectURL(blob) // blob → 临时 URL
    link.download = fileName  // 导出文件名  必须写，否则浏览器直接预览
    document.body.appendChild(link)
    link.click()  // 触发下载
    document.body.removeChild(link)
    window.URL.revokeObjectURL(link.href)  // 释放 blob 内存
  } catch (e) {
    ElMessage.error('导出失败')
  }
}

/* ====== 导入：axios 上传 ====== */
const importSuccess = (res) => {
  ElMessage.success(res.message || '导入成功')  // 后端 Result.success("导入成功") 会带 message
  getData()  // 刷新表格，看不到新数据就这里没调
}
const importError = (err) => {
  ElMessage.error(err.message || '导入失败')
}

/* 表格数据 */
const tableData = ref([])
const loading = ref(false)

/* 分页 */
const pagination = ref({
  currentPage: 1,
  pageSize: 6,
  total: 0 // 后端 Result.success(list, total) 会带 total  后端返回 total，前端自动计算页码
})

/* 搜索条件 */
const queryForm = ref({
  status: null,
  name: '',
  studentNo: '',
  className: '',
  buildingName: '',
  isPaid: null
})

/* 弹窗 */
const dialogVisible = ref(false)
const dialogTitle = ref('')
const formRef = ref(null)
const formData = ref({
  id: null,
  studentNo: '',
  name: '',
  major: '',
  className: '',
  phoneNumber: '',
  buildingName: '',
  dormNo: '',
  reportingStatus: '待报到',
  reportingTime: null,
  isPaid: 0,
  paymentStatus: '',
  paymentTime: null
})

const rules = {
  studentNo: [{ required: true, message: '请输入学号', trigger: 'blur' }],
  name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  className: [{ required: true, message: '请选择班级', trigger: 'blur' }],
  phoneNumber: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '手机号格式错误', trigger: 'blur' }
  ]
}

/* 拉数据 */
const getData = async () => {
  loading.value = true
  const params = { ...queryForm.value, ...pagination.value }
  const res = await getReportingPage(params)
  tableData.value = res.data.list
  pagination.value.total = res.data.total
  loading.value = false
}

/* 分页大小变化 */
const handleSizeChange = (val) => {
  pagination.value.pageSize = val
  getData()
}
const handleCurrentChange = (val) => {
  pagination.value.currentPage = val
  getData()
}

/* 新增/编辑 */
const handleAdd = () => {
  dialogTitle.value = '新增报到'
  resetForm()
  dialogVisible.value = true
}
const handleEdit = (row) => {
  dialogTitle.value = '编辑报到'
  formData.value = { ...row }
  dialogVisible.value = true
}

/* 提交 */
const submitForm = async () => {
  await formRef.value.validate()
  const payload = { ...formData.value }
  payload.reportingTime = payload.reportingTime ? dayjs(payload.reportingTime).format('YYYY-MM-DD HH:mm:ss') : null
  payload.paymentTime = payload.paymentTime ? dayjs(payload.paymentTime).format('YYYY-MM-DD HH:mm:ss') : null
  const api = payload.id ? updateReporting : addReporting
  const res = await api(payload)
  ElMessage.success(res.message)
  dialogVisible.value = false
  getData()
}

/* 删除 */
const handleDelete = (id) => {
  ElMessageBox.confirm('确定删除该报到记录？', '提示', { type: 'warning' })
    .then(async () => {
      const res = await deleteReporting(id)
      ElMessage.success(res.message)
      getData()
    })
    .catch(() => ElMessage.info('已取消'))
}

/* 批量删除 */
const selectedIds = ref([])
const handleSelectionChange = (rows) => {
  selectedIds.value = rows.map(r => r.id)
}
const handleBatchDelete = async () => {
  if (!selectedIds.value.length) return ElMessage.warning('请至少选择一条')
  ElMessageBox.confirm(`将删除 ${selectedIds.value.length} 条数据，继续？`, '提示', { type: 'warning' })
    .then(async () => {
      const res = await batchDeleteReporting(selectedIds.value)
      ElMessage.success(res.message)
      getData()
    })
    .catch(() => ElMessage.info('已取消'))
}

/* 重置 */
const resetForm = () => {
  formData.value = {
    id: null,
    studentNo: '',
    name: '',
    major: '',
    className: '',
    phoneNumber: '',
    buildingName: '',
    dormNo: '',
    reportingStatus: '待报到',
    reportingTime: null,
    isPaid: 0,
    paymentStatus: '',
    paymentTime: null
  }
}

onMounted(() => getData())
</script>

<template>
  <div class="app-container">
    <!-- 搜索区 -->
    <el-form :inline="true" :model="queryForm" class="demo-form-inline">
      <el-form-item label="报到状态">
        <el-select v-model="queryForm.status" placeholder="全部" clearable>
          <el-option label="待报到" value="待报到" />
          <el-option label="报到中" value="报到中" />
          <el-option label="已完成" value="已完成" />
          <el-option label="未报到" value="未报到" />
        </el-select>
      </el-form-item>
      <el-form-item label="姓名">
        <el-input v-model="queryForm.name" placeholder="模糊查询" clearable />
      </el-form-item>
      <el-form-item label="学号">
        <el-input v-model="queryForm.studentNo" placeholder="学号" clearable />
      </el-form-item>
      <el-form-item label="班级">
        <el-input v-model="queryForm.className" placeholder="班级" clearable />
      </el-form-item>
      <el-form-item label="宿舍楼">
        <el-input v-model="queryForm.buildingName" placeholder="宿舍楼" clearable />
      </el-form-item>
      <el-form-item label="缴费状态">
        <el-select v-model="queryForm.isPaid" placeholder="全部" clearable>
          <el-option label="已缴" :value="1" />
          <el-option label="未缴" :value="0" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" :icon="Search" @click="getData">搜索</el-button>
        <el-button :icon="Refresh" @click="queryForm = {}; getData()">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 按钮区 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" :icon="Plus" @click="handleAdd">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" :icon="Delete" @click="handleBatchDelete">批量删除</el-button>
      </el-col>

      <!-- 导入 -->
      <el-col :span="1.5">
        <el-upload action="http://localhost:8080/api/reporting/import" :headers="uploadHeaders" :show-file-list="false"
          :on-success="importSuccess" :on-error="importError" accept=".xlsx,.xls"
          style="display:inline-block; margin-left:10px">
          <el-button type="success" :icon="Download">导入</el-button>
        </el-upload>
      </el-col>

      <!-- 导出 -->
      <el-col :span="1.5">
        <el-button type="info" :icon="Upload" @click="handleExport">导出</el-button>
      </el-col>
    </el-row>

    <!-- 表格 -->
    <el-table v-loading="loading" :data="tableData" @selection-change="handleSelectionChange" row-key="id" size="small">
      <el-table-column type="selection" width="50" align="center" />
      <el-table-column type="index" label="序号" width="60" align="center" />
      <el-table-column prop="studentNo" label="学号" width="110" show-overflow-tooltip />
      <el-table-column prop="name" label="姓名" width="70" show-overflow-tooltip />
      <el-table-column prop="major" label="专业" width="100" show-overflow-tooltip />
      <el-table-column prop="className" label="班级" width="100" show-overflow-tooltip />
      <el-table-column prop="phoneNumber" label="联系电话" width="110" align="center" />
      <el-table-column prop="buildingName" label="宿舍楼" width="90" show-overflow-tooltip />
      <el-table-column prop="dormNo" label="宿舍号" width="80" align="center" />
      <el-table-column prop="reportingStatus" label="报到状态" width="90" align="center">
        <template #default="{ row }">
          <el-tag
            :type="row.reportingStatus === '已完成' ? 'success' : row.reportingStatus === '未报到' ? 'danger' : 'warning'"
            size="small">
            {{ row.reportingStatus }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="isPaid" label="已缴费" width="70" align="center">
        <template #default="{ row }">
          <el-tag :type="row.isPaid === 1 ? 'success' : 'danger'" size="small">
            {{ row.isPaid === 1 ? '是' : '否' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="paymentStatus" label="缴费状态" width="90" show-overflow-tooltip />
      <el-table-column label="操作" min_width="160" fixed="right" align="center">
        <template #default="{ row }">
          <el-button link type="primary" @click="handleEdit(row)">编辑</el-button>
          <el-button link type="danger" @click="handleDelete(row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-config-provider :locale="zhCn">
      <el-pagination background layout="total, sizes, prev, pager, next, jumper"
        v-model:current-page="pagination.currentPage" v-model:page-size="pagination.pageSize" :total="pagination.total"
        @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    </el-config-provider>

    <!-- 新增/编辑弹窗 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="600">
      <el-form ref="formRef" :model="formData" :rules="rules" label-width="100">
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="学号" prop="studentNo">
              <el-input v-model="formData.studentNo" placeholder="学号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="姓名" prop="name">
              <el-input v-model="formData.name" placeholder="姓名" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="专业" prop="major">
              <el-input v-model="formData.major" placeholder="专业" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="班级" prop="className">
              <el-input v-model="formData.className" placeholder="班级" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="联系电话" prop="phoneNumber">
          <el-input v-model="formData.phoneNumber" placeholder="手机号" />
        </el-form-item>
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="宿舍楼" prop="buildingName">
              <el-input v-model="formData.buildingName" placeholder="宿舍楼" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="宿舍号" prop="dormNo">
              <el-input v-model="formData.dormNo" placeholder="宿舍号" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="报到状态" prop="reportingStatus">
              <el-select v-model="formData.reportingStatus" placeholder="请选择" style="width: 100%">
                <el-option label="待报到" value="待报到" />
                <el-option label="报到中" value="报到中" />
                <el-option label="已完成" value="已完成" />
                <el-option label="未报到" value="未报到" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="报到时间" prop="reportingTime">
              <el-date-picker v-model="formData.reportingTime" type="datetime" placeholder="选择日期时间"
                style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="已缴费" prop="isPaid">
              <el-switch v-model="formData.isPaid" :active-value="1" :inactive-value="0" inline-prompt active-text="是"
                inactive-text="否" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <!-- 选择框 -->
            <el-form-item label="缴费状态" prop="paymentStatus">
              <el-select v-model="formData.paymentStatus" placeholder="请选择缴费状态" style="width: 100%">
                <el-option label="全部缴清" value="全部缴清" />
                <el-option label="未缴清" value="未缴清" />
                <el-option label="未缴费" value="未缴费" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="缴费时间" prop="paymentTime">
          <el-date-picker v-model="formData.paymentTime" type="datetime" placeholder="选择日期时间" style="width: 100%" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">提交</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.app-container {
  padding: 20px;
}

.mb8 {
  margin-bottom: 8px;
}
</style>